<template>
  <div>
    <el-card>
      <h2>我的门店列表</h2>

      
      <!-- 新增：状态为0的门店列表 -->
      <h3 style="margin-top:32px;">未提交门店</h3>
      <el-table :data="pagedStatus0List" style="width: 100%; margin-bottom: 32px;">
        <el-table-column label="门店名称">
          <template #default="{ row }">
            {{ row.storeName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="franchisee" label="加盟商" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="address" label="地址" />
        <el-table-column label="加盟日期">
          <template #default="{ row }">
            {{ row.joinDate ? row.joinDate.split('T')[0] : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" header-align="center" align="center">
          <template #default="{ row }">
            <div style="display: flex; justify-content: center; align-items: center; height: 100%;">
              <el-button type="success" size="small" @click="openUploadDialog(row.storeId)">上传资料</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :current-page="status0PageNum"
        :page-size="status0PageSize"
        :total="status0List.length"
        @current-change="handleStatus0PageChange"
        style="margin-bottom: 16px;"
      />
    </el-card>
    
    <!-- 新增：已提交门店模块 -->
    <el-card style="margin-top: 32px;">
      <h3>已提交门店</h3>
      <el-table :data="pagedSubmittedList" style="width: 100%; margin-bottom: 32px;">
        <el-table-column label="门店名称">
          <template #default="{ row }">
            {{ row.storeName || row.franchisee || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="franchisee" label="加盟商" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="address" label="地址" />
        <el-table-column label="加盟日期">
          <template #default="{ row }">
            {{ row.joinDate ? row.joinDate.split('T')[0] : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" header-align="center">
          <template #default="{ row }">
            <div style="display: flex; justify-content: space-between;">
              <el-tooltip content="已上传团购信息" v-if="row.tuangouStatus === 1">
                <el-button type="primary" size="small" :disabled="true">上传团购</el-button>
              </el-tooltip>
              <el-button v-else type="primary" size="small" @click="goToGroupBuy(row.storeId)">上传团购</el-button>
              <el-tooltip content="已上传外卖信息" v-if="row.status === 1">
                <el-button type="primary" size="small" :disabled="true">上传外卖</el-button>
              </el-tooltip>
              <el-button v-else type="primary" size="small" @click="goToTakeout(row.storeId)">上传外卖</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :current-page="submittedPageNum"
        :page-size="submittedPageSize"
        :total="submittedTotal"
        @current-change="handleSubmittedPageChange"
        style="margin-bottom: 16px;"
      />
    </el-card>
    
    <!-- 新增：完成交接模块 -->
    <el-card style="margin-top: 32px;">
      <h3>完成交接</h3>
      <el-table :data="pagedHandoverList" style="width: 100%; margin-bottom: 32px;">
        <el-table-column label="门店名称">
          <template #default="{ row }">
            {{ row.storeName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="franchisee" label="加盟商" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="province" label="省份" />
        <el-table-column prop="address" label="地址" />
        <el-table-column label="加盟日期">
          <template #default="{ row }">
            {{ row.joinDate ? row.joinDate.split('T')[0] : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="是否有团购" align="center">
          <template #default="{ row }">
            {{ row.tuangouStatus === 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" header-align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewHandoverDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :current-page="handoverPageNum"
        :page-size="handoverPageSize"
        :total="handoverList.length"
        @current-change="handleHandoverPageChange"
        style="margin-bottom: 16px;"
      />
    </el-card>
    <el-dialog v-model="dialogVisible" title="门店详情" width="800px" :close-on-click-modal="true">
      <div v-if="detailData && detailData.store">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="门店ID">{{ detailData.store.storeId }}</el-descriptions-item>
          <el-descriptions-item label="门店名称">{{ detailData.store.storeName }}</el-descriptions-item>
          <el-descriptions-item label="加盟商">{{ detailData.store.franchisee }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ detailData.store.phone }}</el-descriptions-item>
          <el-descriptions-item label="省份">{{ detailData.store.province }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ detailData.store.address }}</el-descriptions-item>
          <el-descriptions-item label="加盟日期">{{ formatDateTime(detailData.store.joinDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ detailData.store.status }}</el-descriptions-item>
        </el-descriptions>
        <h4 style="margin-top: 20px;">流程日志</h4>
        <el-table :data="detailData.logs" size="small" border style="width: 100%;">
          <el-table-column prop="logId" label="日志ID" width="80" align="center" />
          <el-table-column prop="submitFromName" label="提交人" align="center" />
          <el-table-column prop="submitToName" label="接收人" align="center" />
          <el-table-column prop="submitTime" label="提交时间" align="center">
            <template #default="{ row }">{{ formatDateTime(row.submitTime) }}</template>
          </el-table-column>
          <el-table-column prop="submitType" label="类型" align="center">
            <template #default="{ row }">
              {{ getSubmissionTypeText(row.submitType) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>暂无数据</div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showNextOperatorDialog" title="请输入下一位操作者名字" width="400px">
      <el-select v-model="nextOperatorName" placeholder="请选择下一位操作者">
        <el-option v-for="item in employee1List" :key="item.employeeId" :label="item.name" :value="item.name" />
      </el-select>
      <template #footer>
        <el-button @click="handleNextOperatorCancel" :disabled="isSubmitting">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleNextOperatorSubmit"
          :loading="isSubmitting"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '提交' }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="joinRemindDialogVisible" title="加盟员工门店信息上传提醒" width="600px" class="join-remind-dialog">
      <div v-if="joinRemindList.length">
        <el-alert type="warning" :closable="false" show-icon class="join-remind-alert">
          <span>以下加盟商需要上传门店信息，请及时处理：</span>
        </el-alert>
        <el-table :data="joinRemindList" style="width: 100%" size="small" border>
          <el-table-column prop="franchisee" label="加盟商" align="center" />
          <el-table-column prop="phone" label="电话号码" align="center" />
          <el-table-column label="加盟日期" align="center">
            <template #default="{ row }">
              {{ row.joinDate ? row.joinDate.split('T')[0] : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160">
            <template #default="{ row }">
              <el-button size="small" @click="showJoinDetail(row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="join-remind-empty">
        <el-empty description="暂无需要上传的加盟商" />
      </div>
      <template #footer>
        <el-button type="primary" @click="joinRemindDialogVisible = false">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="joinDetailDialogVisible" title="加盟商详情" width="420px" class="join-detail-dialog">
      <div v-if="joinDetail" class="join-detail-content">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item v-for="(value, key) in joinDetailAllFields" :key="key" :label="fieldLabels[key] || key">
            <span v-if="value !== undefined && value !== null && value !== ''">{{ value }}</span>
            <span v-else style="color: #f56c6c;">未填</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="join-detail-empty">暂无数据</div>
      <template #footer>
        <el-button @click="joinDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 上传资料弹窗 -->
    <el-dialog v-model="dialogVisibleForUpload" title="上传门店资料" width="900px" :close-on-click-modal="true">
      <div>
        <!-- 这里复用上传团购/外卖的上半部分表单内容 -->
        <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="120px">
          <el-form-item label="门店名称" prop="storeName" required>
            <el-input v-model="uploadForm.storeName" />
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicense" required>
            <UploadImage v-model="uploadForm.businessLicense" />
          </el-form-item>
          <el-form-item label="食品许可证" prop="foodLicense" required>
            <UploadImage v-model="uploadForm.foodLicense" />
          </el-form-item>
          <el-form-item label="手持身份证正反面" prop="idcardHandBoth" required>
            <UploadImage v-model="uploadForm.idcardHandBoth" :limit="2" multiple />
          </el-form-item>
          <el-form-item label="身份证正反面" prop="idcardBoth" required>
            <UploadImage v-model="uploadForm.idcardBoth" :limit="2" multiple />
          </el-form-item>
          <el-form-item label="门头照片" prop="storeFrontPhoto" required>
            <UploadImage v-model="uploadForm.storeFrontPhoto" />
          </el-form-item>
          <el-form-item label="店内环境照片" prop="storeInsidePhotos" required>
            <UploadImage v-model="uploadForm.storeInsidePhotos" :limit="9" multiple />
          </el-form-item>
          <el-form-item label="门店联系电话" prop="storePhone" required>
            <el-input v-model="uploadForm.storePhone" placeholder="请输入11位手机号码" />
          </el-form-item>
          <el-form-item label="银行卡号" prop="bankCardNumber" required>
            <el-input v-model="uploadForm.bankCardNumber" placeholder="请输入16-19位银行卡号" />
          </el-form-item>
          <el-form-item label="结算手机号" prop="bankPhone" required>
            <el-input v-model="uploadForm.bankPhone" placeholder="请输入11位手机号码" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisibleForUpload = false">取消</el-button>
        <el-button type="primary" :loading="isUploading" :disabled="isUploading" @click="submitUploadForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '../store/user';
import { formatDateTime } from '../utils/dateUtils';
import UploadImage from '../components/UploadImage.vue';

const status0List = ref([]); // 状态为0的门店
const submittedList = ref([]); // 已提交门店
const router = useRouter();

const userStore = useUserStore();

const showNextOperatorDialog = ref(false);
const nextOperatorName = ref('');
const currentStoreId = ref(null);
const employee1List = ref([]);
const isSubmitting = ref(false);

// 未提交门店分页相关
const status0PageNum = ref(1);
const status0PageSize = 5;
const pagedStatus0List = computed(() => {
  const start = (status0PageNum.value - 1) * status0PageSize;
  return status0List.value.slice(start, start + status0PageSize);
});
function handleStatus0PageChange(page) {
  status0PageNum.value = page;
}

// 已提交门店分页相关（原有，调整每页5条）
const submittedPageNum = ref(1);
const submittedPageSize = 5;
const submittedTotal = computed(() => submittedList.value.length);
const pagedSubmittedList = computed(() => {
  const start = (submittedPageNum.value - 1) * submittedPageSize;
  return submittedList.value.slice(start, start + submittedPageSize);
});
function handleSubmittedPageChange(page) {
  submittedPageNum.value = page;
}

// 完成交接分页相关
const handoverPageNum = ref(1);
const handoverPageSize = 5;
const pagedHandoverList = computed(() => {
  const start = (handoverPageNum.value - 1) * handoverPageSize;
  return handoverList.value.slice(start, start + handoverPageSize);
});
function handleHandoverPageChange(page) {
  handoverPageNum.value = page;
}

const dialogVisible = ref(false);
const detailData = ref(null);

const joinRemindDialogVisible = ref(false);
const joinRemindList = ref([]);
const joinDetailDialogVisible = ref(false);
const joinDetail = ref(null);
const joinDetailAllFields = computed(() => {
  if (!joinDetail.value) return {};
  // 只展示非ID字段
  const fields = [
    'franchisee', 'phone', 'joinDate', 'province', 'address', 'wechatGroup', 'idNumber',
    'status', 'openingDate', 'createTime', 'tuangouStatus'
  ];
  const result = {};
  for (const key of fields) {
    result[key] = joinDetail.value[key];
  }
  return result;
});
const fieldLabels = {
  franchisee: '加盟商',
  phone: '电话号码',
  joinDate: '加盟日期',
  province: '省份',
  address: '地址',
  wechatGroup: '微信/群',
  idNumber: '身份证号',
  status: '状态',
  openingDate: '开业日期',
  createTime: '创建时间',
  tuangouStatus: '团购状态'
};

// 1. 新增 handoverList 变量
const handoverList = ref([]);

function getEmployee1Name(employee1Id) {
  if (!employee1Id) return '-';
  const emp = employee1List.value.find(e => e.employeeId === employee1Id);
  return emp ? emp.name : '-';
}

function getStageText(status) {
  switch (status) {
    case 1: return '阶段1';
    case 2: return '阶段2';
    case 3: return '阶段3';
    case 4: return '阶段4';
    case 5: return '阶段5';
    default: return '-';
  }
}

function getSubmissionTypeText(type) {
  if (type === 1) return '外卖';
  if (type === 2) return '团购';
  return '-';
}

function goAddStore() {
  router.push('/user/submit');
}

async function fetchStatus0List() {
  try {
    let url = 'http://121.43.176.9:8090/api/store/status0';
    // 判断是否为管理员
    if (Number(userStore.roleCode) !== 3) {
      url += `?createUserId=${userStore.userId}`;
    }
    const res = await fetch(url).then(r => r.json());
    if (res.code === 200) {
      status0List.value = res.data;
    } else {
      status0List.value = [];
    }
  } catch (e) {
    status0List.value = [];
  }
}

async function fetchSubmittedList(page = submittedPageNum.value) {
  try {
    let url = 'http://121.43.176.9:8090/api/store/by-user';
    // 判断是否为管理员
    if (Number(userStore.roleCode) !== 3) {
      url += `?userId=${userStore.userId}`;
    }
    const res = await fetch(url).then(r => r.json());
    if (res.code === 200) {
      submittedList.value = (res.data || []).filter(item =>
        (item.tuangouStatus === null && (item.status === 1 || item.status === 6)) ||
        (item.tuangouStatus === 1 && item.status === 6)
      );
      // submittedTotal.value = res.data ? res.data.length : 0; // This line is now handled by computed property
    } else {
      submittedList.value = [];
      // submittedTotal.value = 0; // This line is now handled by computed property
    }
  } catch (e) {
    submittedList.value = [];
    // submittedTotal.value = 0; // This line is now handled by computed property
  }
}

async function viewDetail(storeId) {
  dialogVisible.value = false;
  detailData.value = null;
  
  // 先找到对应的门店记录，获取创建者ID
  const storeRecord = status0List.value.find(item => item.storeId === storeId);
  if (!storeRecord) {
    ElMessage.error('未找到门店信息');
    return;
  }
  
  // 使用创建者的userId而不是当前登录用户的userId
  const creatorUserId = storeRecord.createUserId;
  
  // 获取用户认证详情
  const res = await fetch(`http://121.43.176.9:8090/api/user-certification/user/${creatorUserId}`).then(r => r.json());
  if ((res.code === 0 || res.code === 200) && res.data) {
    detailData.value = res.data;
    dialogVisible.value = true;
  } else {
    ElMessage.error(res.msg || '未找到认证信息');
  }
}

async function fetchEmployee1List() {
  const res = await fetch('http://121.43.176.9:8090/api/employee/type1/list').then(r => r.json());
  if (res.code === 200) {
    employee1List.value = res.data;
  } else {
    employee1List.value = [];
  }
}

function onEdit(storeId) {
  router.push({ path: '/user/submit', query: { storeId, edit: 1 } });
}

function showJoinDetail(row) {
  joinDetail.value = row;
  joinDetailDialogVisible.value = true;
}

function goToGroupBuy(storeId) {
  router.push({ path: '/user/groupbuy', query: { storeId } });
}
function goToTakeout(storeId) {
  router.push({ path: '/user/takeout', query: { storeId } });
}
function goToUserSubmit(storeId) {
  router.push({ path: '/user/submit', query: { storeId } });
}



const dialogVisibleForUpload = ref(false);
const currentUploadStoreId = ref(null);
const uploadForm = ref({
  storeName: '',
  businessLicense: '',
  foodLicense: '',
  idcardHandBoth: [], // 手持身份证正反面
  idcardBoth: [],     // 身份证正反面
  storeFrontPhoto: '',
  storeInsidePhotos: [], // 多张
  storePhone: '',
  bankCardNumber: '',
  bankPhone: ''
});

// 上传表单验证规则
const uploadRules = {
  storeName: [
    { required: true, message: '请输入门店名称', trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  foodLicense: [
    { required: true, message: '请上传食品许可证', trigger: 'change' }
  ],
  idcardHandBoth: [
    { required: true, message: '请上传手持身份证正反面', trigger: 'change' }
  ],
  idcardBoth: [
    { required: true, message: '请上传身份证正反面', trigger: 'change' }
  ],
  storeFrontPhoto: [
    { required: true, message: '请上传门头照片', trigger: 'change' }
  ],
  storeInsidePhotos: [
    { required: true, message: '请上传店内环境照片', trigger: 'change' }
  ],
  storePhone: [
    { required: true, message: '请输入门店联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  bankCardNumber: [
    { required: true, message: '请输入银行卡号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行卡号', trigger: 'blur' }
  ],
  bankPhone: [
    { required: true, message: '请输入结算手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

const uploadFormRef = ref();
const isUploading = ref(false); // 新增：提交按钮loading和禁用状态

function openUploadDialog(storeId) {
  currentUploadStoreId.value = storeId;
  // 这里可以根据storeId拉取原有数据，或清空表单
  uploadForm.value = {
    storeName: '',
    businessLicense: '',
    foodLicense: '',
    idcardHandBoth: [], // 手持身份证正反面
    idcardBoth: [],     // 身份证正反面
    storeFrontPhoto: '',
    storeInsidePhotos: [], // 多张
    storePhone: '',
    bankCardNumber: '',
    bankPhone: ''
  };
  dialogVisibleForUpload.value = true;
}

function isAllImagesUploaded() {
  // 检查所有图片字段，是否有 raw 状态（即还未上传完成）
  const imgFields = [
    'businessLicense', 'foodLicense', 'idcardHandBoth', 'idcardBoth', 'storeFrontPhoto', 'storeInsidePhotos'
  ];
  for (const key of imgFields) {
    const val = uploadForm.value[key];
    if (Array.isArray(val)) {
      for (const item of val) {
        if (item.status && item.status !== 'success') return false;
      }
    } else if (val && typeof val === 'object') {
      if (val.status && val.status !== 'success') return false;
    }
  }
  return true;
}

async function submitUploadForm() {
  if (isUploading.value) return;
  
  // 表单验证
  try {
    await uploadFormRef.value.validate();
  } catch (error) {
    ElMessage.error('请完善表单信息');
    return;
  }
  
  // 检查图片是否全部上传完成
  if (!isAllImagesUploaded()) {
    ElMessage.warning('请等待所有图片上传完成后再提交');
    return;
  }
  isUploading.value = true;
  // 校验 storeId
  if (!currentUploadStoreId.value) {
    ElMessage.error('缺少门店ID，无法上传');
    return;
  }
  const formData = new FormData();
  formData.append('storeId', currentUploadStoreId.value);
  formData.append('storeName', uploadForm.value.storeName || '');
  formData.append('userId', userStore.userId);
  formData.append('storePhone', uploadForm.value.storePhone || '');
  formData.append('bankCardNumber', uploadForm.value.bankCardNumber || '');
  formData.append('bankPhone', uploadForm.value.bankPhone || '');

  // 营业执照
  if (Array.isArray(uploadForm.value.businessLicense) && uploadForm.value.businessLicense.length > 0) {
    const businessLicense = uploadForm.value.businessLicense[0];
    if (businessLicense.raw instanceof File) {
      formData.append('businessLicenseFile', businessLicense.raw);
    } else if (businessLicense.url) {
      formData.append('businessLicenseUrl', businessLicense.url);
    }
  }
  // 食品许可证
  if (Array.isArray(uploadForm.value.foodLicense) && uploadForm.value.foodLicense.length > 0) {
    const foodLicense = uploadForm.value.foodLicense[0];
    if (foodLicense.raw instanceof File) {
      formData.append('foodLicenseFile', foodLicense.raw);
    } else if (foodLicense.url) {
      formData.append('foodLicenseUrl', foodLicense.url);
    }
  }
  // 手持身份证正反面（多张）
  if (Array.isArray(uploadForm.value.idcardHandBoth) && uploadForm.value.idcardHandBoth.length > 0) {
    if (uploadForm.value.idcardHandBoth[0]?.raw instanceof File) {
      formData.append('idcardHandFrontFile', uploadForm.value.idcardHandBoth[0].raw);
    } else if (uploadForm.value.idcardHandBoth[0]?.url) {
      formData.append('idcardHandFrontUrl', uploadForm.value.idcardHandBoth[0].url);
    }
    if (uploadForm.value.idcardHandBoth[1]?.raw instanceof File) {
      formData.append('idcardHandBackFile', uploadForm.value.idcardHandBoth[1].raw);
    } else if (uploadForm.value.idcardHandBoth[1]?.url) {
      formData.append('idcardHandBackUrl', uploadForm.value.idcardHandBoth[1].url);
    }
  }
  // 身份证正反面（多张）
  if (Array.isArray(uploadForm.value.idcardBoth) && uploadForm.value.idcardBoth.length > 0) {
    if (uploadForm.value.idcardBoth[0]?.raw instanceof File) {
      formData.append('idcardFrontFile', uploadForm.value.idcardBoth[0].raw);
    } else if (uploadForm.value.idcardBoth[0]?.url) {
      formData.append('idcardFrontUrl', uploadForm.value.idcardBoth[0].url);
    }
    if (uploadForm.value.idcardBoth[1]?.raw instanceof File) {
      formData.append('idcardBackFile', uploadForm.value.idcardBoth[1].raw);
    } else if (uploadForm.value.idcardBoth[1]?.url) {
      formData.append('idcardBackUrl', uploadForm.value.idcardBoth[1].url);
    }
  }
  // 门头照片
  if (Array.isArray(uploadForm.value.storeFrontPhoto) && uploadForm.value.storeFrontPhoto.length > 0) {
    const storeFrontPhoto = uploadForm.value.storeFrontPhoto[0];
    if (storeFrontPhoto.raw instanceof File) {
      formData.append('storeFrontPhotoFile', storeFrontPhoto.raw);
    } else if (storeFrontPhoto.url) {
      formData.append('storeFrontPhotoUrl', storeFrontPhoto.url);
    }
  }
  // 店内环境照片（多张）
  if (Array.isArray(uploadForm.value.storeInsidePhotos) && uploadForm.value.storeInsidePhotos.length > 0) {
    let hasFile = false, urlList = [];
    uploadForm.value.storeInsidePhotos.forEach(item => {
      if (item.raw instanceof File) {
        formData.append('storeInsidePhotoFiles', item.raw);
        hasFile = true;
      } else if (item.url) {
        urlList.push(item.url);
      }
    });
    if (urlList.length > 0) {
      formData.append('storeInsidePhotoUrls', urlList.join(','));
    }
  }

  try {
    const res = await fetch('http://121.43.176.9:8090/api/user-certification/upload-all', {
      method: 'POST',
      body: formData
    }).then(r => r.json());
    if (res.code === 200) {
      ElMessage.success('资料上传成功');
      dialogVisibleForUpload.value = false;
      try{
        router.go(0);
      }catch(e){}
      // 新增：上传资料成功后，写入流程日志
      const log = {
        storeId: currentUploadStoreId.value,
        submitFrom: userStore.account,
        submitTo: '-', // 此处无交接人可填空或根据业务补充
        submitTime: new Date().toISOString(),
        stage: 2
      };
      await fetch('http://121.43.176.9:8090/api/log/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(log)
      });
    } else {
      ElMessage.error(res.msg || '上传失败');
    }
  } catch (e) {
    ElMessage.error('上传失败');
  } finally {
    isUploading.value = false;
  }
}

async function viewHandoverDetail(row) {
  // row.storeId 是门店ID
  try {
    // 1. 获取门店详情
    const storeRes = await fetch(`http://121.43.176.9:8090/api/store/detail/${row.storeId}`).then(r => r.json());
    // 2. 获取流程日志
    const logRes = await fetch(`http://121.43.176.9:8090/api/log/by-store?storeId=${row.storeId}`).then(r => r.json());
    // 3. 展示弹窗，内容为门店详情和流程日志
    detailData.value = {
      store: storeRes.data || {},
      logs: logRes.data || []
    };
    dialogVisible.value = true;
  } catch (e) {
    ElMessage.error('获取详情失败');
  }
}

// 2. 新增 fetchHandoverList 方法
async function fetchHandoverList() {
  try {
    let url = 'http://121.43.176.9:8090/api/store/by-user';
    if (Number(userStore.roleCode) !== 3) {
      url += `?userId=${userStore.userId}`;
    }
    const res = await fetch(url).then(r => r.json());
    if (res.code === 200) {
      const filtered = (res.data || []).filter(item => 
        [1, 2, 3, 4, 5].includes(item.status) && item.tuangouStatus !== null
      );
      // 按加盟时间排序，时间越靠后的排在越前面
      handoverList.value = filtered.sort((a, b) => {
        const dateA = new Date(a.joinDate || 0);
        const dateB = new Date(b.joinDate || 0);
        return dateB - dateA; // 降序排列，最新的在前
      });
    } else {
      handoverList.value = [];
    }
  } catch (e) {
    handoverList.value = [];
  }
}

onMounted(() => {
  fetchStatus0List();
  fetchSubmittedList();
  fetchHandoverList();
  // 加盟员工门店上传提醒
  // fetch(`http://121.43.176.9:8090/api/store/pending-join?userId=${userStore.userId}`)
  //   .then(r => r.json())
  //   .then(res => {
  //     if (res.tag == 1) {
  //       joinRemindList.value = res.data.records;
  //       joinRemindDialogVisible.value = true;
  //     }
  //   });
});
</script>